/*
 * @Author: zhang zhijiang 2824735304@qq.com
 * @Date: 2024-12-03 21:05:18
 * @LastEditors: zhang zhijiang 2824735304@qq.com
 * @LastEditTime: 2024-12-04 21:52:11
 * @FilePath: /linux/test_12_3/pipe.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<cstdio>
#include<unistd.h>
#include<string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<cstdlib>
using namespace std;

#define size 1024
void writer(int wfd)
{
     char buffer[size];
string  mes = "hello linux";
        pid_t pid = getpid();
        int number=0;
        while(true)
        {
            buffer[0] = 0;
            snprintf(buffer,sizeof(buffer),"%s-%d-%d\n",mes.c_str(),pid,number);
            write(wfd,buffer,strlen(buffer));//字符串输入，不关心\n
            // cout<<buffer<<endl;
            number++;
            sleep(1);
        }
}
void reader(int rfd)
{
    char buffer[size];
    while(true)
    {
        buffer[0] = 0;
        int n = read(rfd,buffer,sizeof(buffer));//buffer为输出型参数
        if(n<0)
        return ;
        //将读取到的内容当做字符串使用
        if(n>0)
        buffer[n] =0;
        cout<<buffer<<endl;
    }
    
}
int main()
{
   //创建管道
    int pipefd[2];
    int n = pipe(pipefd);
    // cout<<pipefd[0]<<pipefd[1]<<endl;
    pid_t id = fork();
    if(id==0)//子进程用于写
    {
          close(pipefd[0]);
        writer(pipefd[1]);
      
        
        exit(1);
    }

    close(pipefd[1]);
    //父进程用于读
    reader(pipefd[0]);
    pid_t rid = waitpid(id,nullptr,0);
    if(rid<0)
    return 1;
    return 0;
}